#pragma once
#include <boost/thread.hpp>
#include <boost/atomic.hpp>
class CNetDataHander
{
	typedef SharedPointer<ZMVector<unsigned char>> PVData;
public:
	CNetDataHander();
	~CNetDataHander();
	void DataCommit(PVData pData)
	{
		m_dataLock.lock();
		m_lsData.push_back(pData);
		m_dataLock.unlock();
		HanderData();
	}

	static SharedPointer<CNetDataHander> GetInstance()
	{
		if (!m_pDatahander.get())
		{
			m_pDatahander = SharedPointer<CNetDataHander>(new CNetDataHander());
		}
		return m_pDatahander;
	}

protected:
	void HanderData()
	{
		if (!m_isHanderData)
		{
			m_isHanderData = true;
			boost::thread t(boost::bind(&CNetDataHander::HanderDataCore, this));
		}
	}
	void HanderDataCore()
	{
		m_isHanderData = true;
		PVData pData;
		do 
		{
			pData = PopData();
			if (pData.get())
			{
				HanderOneData(pData);
			}
		} while (pData.get());
		m_isHanderData = false;
	}

	bool IsHaveData()
	{
		bool ret;
		m_dataLock.lock();
		ret = !m_lsData.empty();
		m_dataLock.unlock();
		return ret;
	}

	PVData PopData()
	{
		PVData pRet;
		if(IsHaveData())
		{
			m_dataLock.lock();
			if (!m_lsData.empty())
			{
				pRet = *(m_lsData.begin());
				m_lsData.pop_front();
			}
			m_dataLock.unlock();
		}
		return pRet;
	}

	void HanderOneData(PVData data);
private:
	list<PVData> m_lsData;
	boost::mutex m_dataLock;
	static SharedPointer<CNetDataHander> m_pDatahander;
	boost::atomic<bool> m_isHanderData;
};

